//
//  ST_BTAppConst.swift
//  BTVideo
//  Created by DouLei on 2019/7/9.
//  Copyright © 2019 DouLei. All rights reserved.
//

import Foundation
import DeviceKit
import SwifterSwift
import SwiftyUserDefaults
import SDWebImage
import SwiftyJSON
import AdSupport
import AppTrackingTransparency

//MARK: - Common Value
enum ST_SEX:Int {
    case unkown = 0,male = 1,female = 2,both = 3
    
    
    func SexImage() -> UIImage {
        
        if self == .female{
            return ST_ImageUtils.imageName("homePage_女")!
        }else{
            return ST_ImageUtils.imageName("homePage_男")!
        }
    }
    
    func sexStr()->String{
        
        switch self {
        case .male:
            return "男"
        case .female:
            return "女"
        case .both:
            return "男女"
        default:
            return "未知"
        }
        
    }
}


//MARK: - device
let iPhoneXSeries:Bool = {
    
    if ScreenHeight > 736{
        return true
    }
    
    return false
}()


let iPhonePlusSeries:Bool = {
    if ScreenWidth > 375{
        return true
    }
    
    return false
}()

let BTSafeAreaBottom:CGFloat = {
    if iPhoneXSeries {
        return 34
    }else{
        return 0
    }
}()

let appVersion:String = {
    let version  = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
    return version
}()

let statusBarHeight:CGFloat = {
    if iPhoneXSeries {
        return 44
    }else{
        return 20
    }
}()


let navigationBarHeight:CGFloat = {
    return 44
}()

let  ScreenBounds:CGRect = {
    return UIScreen.main.bounds
}()

let ScreenHeight:CGFloat = {
    return UIScreen.main.bounds.height
}()

let ScreenWidth:CGFloat = {
    return UIScreen.main.bounds.width
}()


/**
 适配机型，间距，Size 等
 */
func TIANCompatibleValue(value:CGFloat)->CGFloat{
    return value/375.0*ScreenWidth
}


/**
 隐身模式
 */
var IS_INVISIBLE = false


//MARK: - Objective-c Use Const  以及基础数据变量

let SC = ST_SwiftConst.shared


@objcMembers
public class ST_SwiftConst: NSObject {
    
    static let shared = ST_SwiftConst()
    
    public static var StatusBarHeight:CGFloat = {
        return statusBarHeight
    }()
    
    public static var _iPhoneXSeries:Bool = {
        return iPhoneXSeries
    }()
    
    public static var _screenWidth:CGFloat = {
        return ScreenWidth
    }()
    
    public static var _screenHeight:CGFloat = {
        return ScreenHeight
    }()
    
    ///今日缘分？
    lazy var toast_fate_chat_config = JSON.null
    
    lazy var tian_token_key = "tian_token_key_312"
    
    /// lot 动态资源前缀
    lazy var lot_resource_prefix = "http://btstatic-cdn.jingniaoapps.com"

    lazy var tian_im_token_key = "tian_im_token_key_version_343"
    
    //    真人认证图标
    //    lazy var YYFaceSignImage = ST_ImageUtils.imageName("首页_icon_认证")!
    
    //    真人new
    lazy var YYFaceSignImage = ST_ImageUtils.imageName("真人new_small")!
    
    //    会员图标
    lazy var  YYMemberSignImage = ST_ImageUtils.imageName("首页__会员标示_大")!
    /// 女神图标
    lazy var  YYGoddessSignImage = ST_ImageUtils.imageName("goddess_icon_mid")!
    
    /// 语音视频通话日志 上报次数 后台字段call_try_time
    /// default value = 3
    lazy var dateLogTryTime = 3
    
    ///支付数据重试时间间隙
    lazy var provide_content_try_times = [3,10,30,60,100]
    
    lazy var secretaryJson = JSON.null
    
    /// 需要检查的订单
    var need_check_o_t_n: String?
    
    /// 首页榜单隐藏
    var hidden_home_trophy = true
    
    fileprivate lazy var placeHolderImageArray:[UIImage] = {
        
        let images = Array(0...6).map { (idx) -> UIImage in
            let name = "placeholder" + idx.string
            return UIImage.init(named: name) ?? UIImage()
        }
        
        return images
    }()
    
    
    fileprivate(set) lazy var numberOptions:[ST_GiftNumberStruct] = {
        return [ST_GiftNumberStruct(number: 1, text: "一心一意"),ST_GiftNumberStruct(number: 10, text: "十全十美"),ST_GiftNumberStruct(number: 30, text: "我想你了"),ST_GiftNumberStruct(number: 66, text: "一切顺利"),ST_GiftNumberStruct(number: 188, text: "要抱抱"),ST_GiftNumberStruct(number: 520, text: "我爱你"),ST_GiftNumberStruct(number: 1314, text: "一生一世"),ST_GiftNumberStruct(number: 3344, text: "生生世世")].reversed()
    }()
    
    //svga临时目录
    fileprivate(set) lazy var svga_temporary_directory:URL? = {
        
        let fileManager = FileManager.default
        
        guard var fileDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else{
            return nil
        }
        
        fileDirectory.appendPathComponent("giftSvgaTem", isDirectory: true)
        
        if !fileManager.fileExists(atPath: fileDirectory.path) {
            do {
                try fileManager.createDirectory(atPath: fileDirectory.path, withIntermediateDirectories: true, attributes: nil)
            } catch {
                print("Couldn't create peculiarityTempMedia directory")
                return nil
            }
        }
        return fileDirectory
    }()
    
    fileprivate func fetch_place_holder_image(index:Int)->UIImage? {
        
        return self.placeHolderImageArray[safe:index]
    }
    
    func fetch_random_place_holder_image()->UIImage? {
        
        let idx = Int.random(in: 0...6)
        
        return fetch_place_holder_image(index: idx)
    }
    
    func fetch_my_local_avatar_image()->UIImage? {
        
        if let img = SDImageCache.shared.imageFromCache(forKey: "myAvatar.png"){
            
            let w = min(img.size.width,img.size.height)
            
            let rounded = img.cropped(to: CGRect.init(x: (img.size.width-w)/2.0, y: (img.size.height-w)/2.0, width: w, height: w)).withRoundedCorners()
            
            return rounded
        }else{
            return nil
        }
    }
    
    var tianIDFA:String{
        
        if let str = Defaults[.idfa]{
            return str
        }
        
        if Defaults[.agreeLicense] == false{
            return ""
        }
        
        // Check whether advertising tracking is enabled
        if #available(iOS 14, *) {
            
            switch ATTrackingManager.trackingAuthorizationStatus {
            case .notDetermined:
                
                print("采集用户设备信息 tracking IDFA Authorization")
                ATTrackingManager.requestTrackingAuthorization { _ in }
                return ""
            case .authorized:
                
                print("采集用户设备信息  IDFA authorized")
                
                let sID = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                
                Defaults[.idfa] = sID
                
                return sID
            default:
                print("采集用户设备信息  IDFA == ''")
                return ""
            }
            
        } else {
            
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled == false {
                return ""
            }else{
                let sID = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                
                Defaults[.idfa] = sID
                
                return sID
            }
        }
    }
    
    func load_lot_base_image(){
        
        
        let keyArray = ["sdd27832sds33fhws","3uk5pd61602226784","akbn4r1602226840","pk03n7a1602226889","mv7c5zh1602226923","b4wg9pn1602226946","bfh3dzc1602226980","ee87s51602227034","abheqop1602227060","6nn5kbj1602227087","ih7a9591602227140","0wcgwyp1602227175","2g15vga1602227205","sdd27832sds33fhws","ee87s51602227034","abheqop1602227060","6nn5kbj1602227087","ih7a9591602227140","0wcgwyp1602227175","2g15vga1602227205"]
        
        keyArray.forEach { (contentKey) in
            
            let urlStr = self.lot_resource_prefix + "/" + contentKey
            
            guard let url = urlStr.url else{
                return
            }
            
            SDWebImageManager.shared.loadImage(with: url, options: SDWebImageOptions.init(), progress: nil) { (img, data, err, type, f, url) in
                
#if DEBUG
                if img != nil{
                    
                    print("基础数据cache成功:",url ?? "错误" )
                    
                }
#endif
                
                
            }
        }
        
    }
    
    func fetch_lot_image(keyStr:String)->UIImage?{
        
        guard let contentKey = keyStr.components(separatedBy: "_").last else{
            return nil
        }
        
        let urlStr = lot_resource_prefix + "/" + contentKey
        
        guard let url = urlStr.url else{
            return nil
        }
        
        let key = SDWebImageManager.shared.cacheKey(for: url)
        
        return SDImageCache.shared.imageFromCache(forKey: key)
        
        
    }
    
    
    func save_my_avatar_image(url:URL){
        
        SDWebImageManager.shared.loadImage(with: url, options: SDWebImageOptions(), progress: nil) { (img, data, err, type, f, url) in
            
            guard let myAvatar = img else{
                return
            }
            //            另存为 myAvatar.png
            SDImageCache.shared.store(myAvatar, forKey: "myAvatar.png") {
                
            }
        }
        
    }
    
    lazy var baidu = ST_BaiduFaceConfig()
    
    lazy var home_search_history_list_key = "HomeSearchHistoryListKey"
    
    
    
    //发布特质临时目录
    lazy var push_peculiarity_directory:URL? = {
        
        let fileManager = FileManager.default
        
        var fileDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
        
        fileDirectory.appendPathComponent("peculiarityTempMedia", isDirectory: true)
        
        if !fileManager.fileExists(atPath: fileDirectory.path) {
            do {
                try fileManager.createDirectory(atPath: fileDirectory.path, withIntermediateDirectories: true, attributes: nil)
            } catch {
                NSLog("Couldn't create peculiarityTempMedia directory")
                return nil
            }
        }
        return fileDirectory
    }()
    
    ///女性节日图标
    var festival_female_icon:String?
    
    ///男性节日图标
    var festival_male_icon:String?
    
    ///根据性别获取 节假日头像👤
    func festivalIcon(gender:Int) -> String? {
        gender == 1 ? festival_male_icon : festival_female_icon
    }
    
}


struct ST_BaiduFaceConfig{
    //LICENSE 文件名
    let FACE_LICENSE_NAME = "***"
    //LICENSE 文件名后缀
    let FACE_LICENSE_SUFFIX = "***"
    //LICENSE_ID
    let FACE_LICENSE_ID = "***"
}

struct ST_GiftNumberStruct {
    let number:Int
    let text:String
}

